<!--蓝底白字-->
<template>
  <div class="main-div" >
    <div>
      <Row :gutter="1">
        <Col span="6">
          <select class="select-custom" v-model="online" :placeholder="h5.onlineSelect">
            <option v-for="item in h5.onlineList" :value="item.value" :key="item.value">{{ item.label }}</option>
          </select>
        </Col>
        <Col span="18">
          <Input id="input-device-search"  search clearable
                 v-model="srhValue" @on-search="search" :placeholder="h5.keyword" />
        </Col>
      </Row>
    </div>

    <Tree id="custom-device-tree"
          :data="deviceData"
          :load-data="loadData"
          :render="renderContent"
          :select-node="selectNode"
          @on-select-change="changeNode" expand-node ></Tree>
  </div>
</template>
<script>
import Device from '@/api/Device';
import Comera from "@/assets/images/comera0.png";
import PoptipBtn from "@/view/Home/map/RelationButton";
import {solveGps} from "@/view/Home/map/maptools/tool/GpsUtils";
import {apiResult} from "@/libs/util";
export default {
  name:"GbOrgDeviceTree",
  components: {PoptipBtn},
  watch:{
    online(){
      this.search();
    },
    deviceData(){
      this.$emit("device-refresh",this.deviceData);
    },
/*    deviceStatus(o,n){
      console.log(o);
      console.log(n);
    },*/
/*    '$store.state.deviceStatus'(newVal, oldVal) {
      // 处理数据变化的逻辑
      console.log('deviceStatus changed oldVal=%o;newVal=%o', oldVal,newVal);
    },*/
    deviceStatus(newVal, oldVal){
      //console.log('deviceStatus changed oldVal=%o;newVal=%o', oldVal,newVal);
      //console.log(this.deviceData);
      this.syncDeviceOnlineStatus(this.deviceData,newVal);
      //console.log('after')
      //console.log(this.deviceData)
    }
  },
  computed:{
    h5(){
      return{
        onlineSelect:this.$t('all'),
        onlineList:[
          {value:0,label:this.$t('all')},{value:1,label:this.$t('online')},{value:-1,label:this.$t('offline')}
        ],
        keyword: this.$t('keyword')
      }
    },
    deviceStatus(){
      return this.$store.getters.getDeviceStatus;
    }

  },
  data(){
    return{
      api: new Device(),
      srhValue: null,
      deviceData: [],
      buttonProps: {
        type: 'primary',
        size: 'small',
      },
      selectNode: false,
      imgSrc:Comera,

      online:0
    }
  },
  methods:{

    /**
     * 同步设备状态
     */
    syncDeviceOnlineStatus(data,statusData){
      //console.log("1.data=%o,statusData=%o",data,statusData)
      if (!!data){
        data.forEach(item=>{
          if (item.type != 'chn'){
            if (!!item.children && item.children.length > 0){
              if (this.syncDeviceOnlineStatus(item.children,statusData) === true){
                return true;
              }
            }
          }else{
            //console.log("2.item=%o",item)
            //console.log("code=%o;deviceCode=%o",item.arrt.deviceCode,statusData.deviceCode)
            if (item.arrt.deviceCode == statusData.deviceCode){
              if (statusData.action == 1){
                item.online = '1'
              }else{
                item.online = '0'
              }
              //console.log("update")
              //console.log(this.deviceData);
              return true;
            }
          }
        });
      }
      return false;
    },
    orgClick(node, data){
      //console.log("orgClick: %o",data);
    },
    devClick(node, data){
      //console.log("devClick: %o",data);
    },
    chnOnlineClick(node, data){
      //在线设备
    },
    chnOfflineClick(node, data){
      //console.log("chnOfflineClick: %o",data);
    },

    loadData(item, callback){
      const that = this;
      let param = {id:item.id};
      this.loading = true;
      //console.log(param);
      this.api.findDeviceForOrgTree(param).then(res=>{
          apiResult(res.data,false,result=>{
            const data1 = that.resoleData(result.data)
            //console.log(">>>>>>>> GbOrgDeviceTree.loadData: data1=%o",data1);
            callback(data1);
            this.$emit("device-refresh",this.deviceData);
          },err=>{
            this.loading = false;
          })
      });

    },

    /**
     * 搜索
     */
    search(){
      if (!!this.srhValue || this.online!=0){
        const that=this;
        const param={keyword:this.srhValue,state:this.online};
        this.api.findDeviceByKeyword(param).then(res=>{
          apiResult(res.data,false,result=>{
            this.deviceData = that.resoleData0(this.deviceData = that.resoleData0(result.data))
          })
        });
      }else{
        this.top();
      }
    },
    /**
     * 第一级数据
     */
    top(){
      const that = this;
      this.api.findDeviceForOrgTree({}).then(res=>{
          apiResult(res.data,false,result=>{
            this.deviceData = that.resoleData(result.data);
          })
      });
    },
    resoleData0(originList){
      if (!originList){originList}
      for(let i in originList){
        if (!!originList[i].longitude && originList[i].longitude>0.0){
          if (!!originList[i].coordinateSystem){
            const gpsData = solveGps(
              //"WGS84",
              originList[i].coordinateSystem,
              parseFloat(originList[i].latitude),
              parseFloat(originList[i].longitude));
            originList[i].longitude=gpsData.lon;
            originList[i].latitude=gpsData.lat;
          }
        }
        if (!!originList[i].children){
          this.resoleData0(originList[i].children);
        }
      }
      return originList
    },
    /**
     * 数据转换
     * @param originList  原数据
     */
    resoleData(originList){
      let target = [];
      if (!!originList){
        let gpsData=null;
        for(let i in originList){
          let data = new Object();
          data.id=originList[i].id;
          data.title=originList[i].title;
          data.type=originList[i].type;
          //转换坐标系
          if (!!originList[i].longitude && originList[i].longitude>0.0){
            //console.log(">>>>>>>> GbOrgDeviceTree.resoleData： originList[%o]=%o",i,originList[i]);
            if (!!originList[i].coordinateSystem){
              gpsData = solveGps(
                //"WGS84",
                originList[i].coordinateSystem,
                parseFloat(originList[i].latitude),
                parseFloat(originList[i].longitude));
              //console.log(">>>>>>>> GbOrgDeviceTree.resoleData： gpsData=%o",gpsData);
              data.longitude=gpsData.lon;
              data.latitude=gpsData.lat;
            }else{
              data.longitude=originList[i].longitude;
              data.latitude=originList[i].latitude;
            }
          }

          if (data.type == "chn"){
            data.online = originList[i].online;
          }

          if (!(originList[i].children == null || originList[i].children==undefined)){
            data.loading=false;
            data.children=[];
          }
          if (!(originList[i].arrt == null || originList[i].arrt==undefined)){
            data.arrt=originList[i].arrt;
          }
          //console.log(">>>>>>>> GbOrgDeviceTree.resoleData： resultdata=%o",data);
          target.push(data);
        }
      }
      return target;
    },

    changeNode(nodes,node){
      /** 这个方法没起作用了*/
      this.$emit('on-select-change', node, node);
    },
    /** Render 渲染 */
    renderContent(h, { root, node, data }){
      if (data.type == 'org'){
        return (
          <span class="node-org-span-1" title={data.title}
                onclick={()=>{
                  this.$emit('org-node-click', node, data)
                }}>{data.title}
          </span>
        )
      }else if (data.type == 'dev'){
        /** 点击设备，NVR等 */
        return (
          <span class="node-dev-span-1" title={data.title}
                onclick={()=>{
                  this.$emit('dev-node-click', node, data)
                }}
          >{data.title}</span>
        )
      }else if (data.type == 'chn' && ('1' == data.online || 'true' == data.online)){
        /** 在线的通道 */
        return(
          <Poptip trigger="hover" placement="right" width="240" props={{transfer:true}}>
            <span class="chn-span-online" title={data.title}
                 onclick={()=>{
                    this.$emit('chn-node-click', "locate",node, data)
                 }}
            >{data.title}</span>
            <div class="poptip-div" slot="content">
              <PoptipBtn props={{status:1,favroteTitle:this.$t('device_favorite')}}//
                         onBtnClick={(event)=>{ //需要这么写，对应的是组件<PoptipBtn> this.$emit('btnClick', event)
                           this.$emit('chn-node-click',event,node, data)
                         }}
              >
              </PoptipBtn>
            </div>
          </Poptip>
        )
      }else{
        return (
          <Poptip trigger="hover" placement="right" width="200" props={{transfer:true}}>
            <span class="chn-span-offline" title={data.title}
                  onclick={()=>{
                    this.$emit('chn-node-click', "locate",node, data)
                  }}
            >{data.title}</span>
            <div class="poptip-div" slot="content">
              <PoptipBtn props={{status:0,favroteTitle:this.$t('device_favorite')}}//'设备收藏'
                         onBtnClick={(event)=>{ //需要这么写，对应的是组件<PoptipBtn> this.$emit('btnClick', event)
                           //console.log(">>>>>>>>> GbOrgDeviceTree.renderContent.onBtnClick： data=%o",data);
                           this.$emit('chn-node-click', event,node, data)
                         }}
              >
              </PoptipBtn>
            </div>
          </Poptip>
        )

      }
    },
  },
  mounted() {
    this.top();
  }
}

</script>
<!--<style lang="less" scoped>-->
<style lang="less" scoped>
/*父组件中添加scoped之后，父组件的样式将不会渗透到子组件中，所以在父组件中写子组件的样式是无效果的
https://blog.csdn.net/weixin_49707375/article/details/128220394
*/

/** Tree.node的CSS*/


//@import "./topnav";

/*
.ivu-icon{
  color: #2d8cf0  !important;
}
.select-custom{
  width: 100%;
  height: 100%;
  background-color: #001529;
  color:#e0e0e0;
  !*清除select的边框样式*!
  border: none;
  !*清除select聚焦时候的边框颜色*!
  outline: none;
}


#input-device-search /deep/ .ivu-input{
  border: 1px solid #244980;
  color: #515a6e ;
  background-color: #001529 ;
}

.ivu-select-dropdown {
  background-color: #051f70ff;
}
.ivu-select-item {
  color: rgba(240, 241, 246, 0.87);
}

.ivu-select-selection {
  background-color: #051f70ff;
}

.ivu-select-item-selected, .ivu-select-item-selected:hover {
  color: #2d8cf0;
}

#custom-device-tree .ul .li:hover{
  color: #78aee4;
}*/
</style>

<style lang="less">
@import "GbOrgDeviceTree-bright";


</style>
